package me.numark.fragments;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.marshalchen.ultimaterecyclerview.UltimateViewAdapter;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.numark.R;
import me.numark.activities.ArticleDetailActivity;
import me.numark.activities.LabelsLikeActivity;
import me.numark.activities.MarkDetailActivity;
import me.numark.activities.ProfileActivity;
import me.numark.model.Feed;
import me.numark.model.FeedListResponse;
import me.numark.model.LabelMsg;
import me.numark.model.LabelMsgListResponse;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.Utils;
import me.numark.view.BaseViewHolder;
import me.numark.view.CircleImageView;

/**
 * Created by Evan on 15/8/8.
 */
public class NoticeLikeFragment extends BaseListFragment {

    SimpleAdapter mLikeAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataList = new ArrayList();
        mLikeAdapter = new SimpleAdapter(this, dataList);
        mAdapter = mLikeAdapter;
    }

    @Override
    public void initUI(View view) {
        super.initUI(view);
        recyclerView.setBackgroundColor(Color.WHITE);
    }

    @Override
    public void loadMore(int itemsCount, int maxLastVisiblePosition) {
        super.loadMore(itemsCount, maxLastVisiblePosition);
        loadData(itemsCount);
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        loadData(0);
    }

    @Override
    protected String cacheKey() {
        return "notice_like";
    }

    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, FeedListResponse.class);
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        LabelMsgListResponse resp = (LabelMsgListResponse) response;
        if (isNew) {
            mLikeAdapter.clear();
        }
        mLikeAdapter.append(resp.data);
        setHasMore(resp.has_more);
    }

    protected void loadData(final int start) {
        if (needLogin && Global.currentUser == null) {
            endRefreshing();
            showEmptyView();
            return;
        }
        new RequestServerTask<LabelMsgListResponse>(LabelMsgListResponse.class,NoticeLikeFragment.this,getString(R.string.please_wait_amoment)) {
            @Override
            protected String requestServer() {
                String url = String.format(NetworkConstants.MY_NOTICE, Global.getCurrentUid());
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("start", String.valueOf(start));
                params.put("limit", String.valueOf(Constants.PAGE_SIZE));
                if (start > 0 && lastResponseTime > 0) {
                    params.put("time", String.valueOf(lastResponseTime));
                }
                return HttpUtil.get(url, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(LabelMsgListResponse result) {
                bindData(result, start == 0);
            }
        }
                .setSnackbarView(rootView)
                .start();
    }

    public class SimpleAdapter extends UltimateViewAdapter<SimpleViewHolder> {

        List<LabelMsg> dataList;
        Object mParent;

        public SimpleAdapter(Object parent, List<LabelMsg> dataList) {
            this.dataList = dataList;
            mParent = parent;
        }

        @Override
        public SimpleViewHolder getViewHolder(View view) {
            return new SimpleViewHolder(view, mParent, true);
        }

        @Override
        public SimpleViewHolder onCreateViewHolder(ViewGroup parent) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.msglike_list_item, parent, false);
            SimpleViewHolder vh = new SimpleViewHolder(v, mParent, false);
            return vh;
        }

        @Override
        public int getAdapterItemCount() {
            return dataList.size();
        }

        @Override
        public long generateHeaderId(int i) {
            return 0;
        }

        @Override
        public void onBindViewHolder(SimpleViewHolder holder, int position) {
            if (position < dataList.size()) {
                LabelMsg labelMsg = dataList.get(position);
                holder.bindData(labelMsg);
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
            return null;
        }

        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int i) {

        }

        public void append(LabelMsg item) {
            insert(dataList, item, dataList.size());
        }

        public void append(LabelMsg[] items) {
            int pos = dataList.size();
            for (LabelMsg item : items) {
                if (item.from_user != null)
                    dataList.add(item);
            }
            notifyItemRangeInserted(pos, items.length);
        }

        public void remove(int position) {
            remove(dataList, position);
        }

        public void clear() {
            clear(dataList);
        }
    }

    public class SimpleViewHolder extends BaseViewHolder {

        @Bind(R.id.avatar)
        public CircleImageView avatar;

        @Bind(R.id.name)
        public TextView name;

        @Bind(R.id.date)
        public TextView date;

        @Bind(R.id.notice_point)
        ImageView noticePoint;

        public SimpleViewHolder(View itemView, Object parent, boolean skip) {
            super(itemView, parent);
            if (skip)
                return;
            ButterKnife.bind(this, itemView);
            avatar.setBorderWidth(2);
            avatar.setBorderColor(Global.avatarColor);
            itemView.setOnClickListener(this);
            addOnClickListener(avatar);
        }

        private LabelMsg mLabelMsg;

        public void bindData(LabelMsg labelMsg) {
            mLabelMsg = labelMsg;
            if (mLabelMsg.status == Global.HAS_READ){
                noticePoint.setVisibility(View.GONE);
            }else {
                noticePoint.setVisibility(View.VISIBLE);
            }

            Picasso.with(getActivity()).load(labelMsg.from_user.pic).into(avatar);
            date.setText(Utils.getDatetimeStr(labelMsg.create_timestamp * 1000));

            SpannableString nameStr = mLabelMsg.from_user.getNameInFeed();
            nameStr.setSpan(new ForegroundColorSpan(Color.rgb(153,153,153)), 0, nameStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            String actionText = "";
            switch (mLabelMsg.type) {
                case 0:
                    actionText = getString(R.string.add_a_label);
                    break;
                case 1:
                    actionText = getString(R.string.vote_you_label);
                    break;
            }
            SpannableString actionStr = new SpannableString(actionText);
            actionStr.setSpan(new RelativeSizeSpan(0.9f), 0, actionStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
           // name.setText(TextUtils.concat(nameStr, actionStr), TextView.BufferType.SPANNABLE);
            SpannableString labelStr = new SpannableString("#"+mLabelMsg.label.title+"#");
            labelStr.setSpan(new ForegroundColorSpan(Color.parseColor("#00b16a")),0,labelStr.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            name.setText(TextUtils.concat(nameStr,actionStr,labelStr),TextView.BufferType.SPANNABLE);



        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.msg_view: {
                    new RequestServerTask<BaseResponse>(BaseResponse.class){
                        @Override
                        protected String requestServer() {
                            String url = String.format(NetworkConstants.MSG_HAS_READ_LIKE,mLabelMsg.id);
                            return HttpUtil.get(url,null);
                        }

                        @Override
                        protected void onSuccess(BaseResponse result) {

                        }
                    }.start();

                    if (mLabelMsg.status == Global.NOT_READ) {
                        mLabelMsg.status= Global.HAS_READ;
                        noticePoint.setVisibility(View.INVISIBLE);
                    }
                    if (mLabelMsg.type == 0) {
                        Intent intent = new Intent(getActivity(), MarkDetailActivity.class);
                        intent.putExtra(Constants.FEED_EXTRA, mLabelMsg.timeline.toString());
                        intent.putExtra(MarkDetailActivity.EXTRA_ORIG_TYPE, Constants.FEEDTYPE_USER_LIKES);
                        if (mLabelMsg.timeline.id==0){
                            intent.putExtra(Constants.NOTICE_IS_NEWS,true);
                        }else {
                            intent.putExtra(Constants.NOTICE_IS_NEWS,false);
                        }
                        // intent.putExtra(Constants.NEWS_EXTRA,mFeed.news.toString());
                        startActivity(intent);
                    }else if (mLabelMsg.type == 1){
                        Intent intent = new Intent(getActivity(), LabelsLikeActivity.class);
                        intent.putExtra(Constants.FEEDTAG_EXTRA,mLabelMsg.label.toString());
                        startActivity(intent);
                    }
                }
                break;
                case R.id.avatar:
                    ProfileActivity.openProfile(getActivity(), mLabelMsg.from_user.uid);
                    break;
            }
        }
    }
}
